<?php

// 后台用户模块
class AccessAction extends CommonAction {

    function _filter(&$map) {
        // admin 用户必须是id=1的。
        //$map['id'] = array('egt',1);
        // $map['user_id'] = array('egt',2);
        /*
          if(!empty($_POST['account'])) {
          $map['account'] = array('like',"%".$_POST['account']."%");
          }
         */
    }

    // 检查帐号
    public function checkAccount() {
        if (!preg_match('/^[a-z]\w{4,}$/i', $_POST['account'])) {
            $this->error('用户名必须是字母，且5位以上！');
        }
        $User = M("User");
        // 检测用户名是否冲突
        $name = $_REQUEST['account'];
        $result = $User->getByAccount($name);
        if ($result) {
            $this->error('该用户名已经存在！');
        } else {
            $this->success('该用户名可以使用！');
        }
    }

    function edit() {
        // 修改
        $name = $this->getActionName();
        $model = M($name);
        $id = $_REQUEST [$model->getPk()];
        $vo = $model->getById($id);
        $role_id = $vo[role_id];
        $vo[vv] = $vo[node_id] . "#" . $vo[level] . "#" . $vo[pid];
        // 取角色表
        $Model2 = M('role');
        //$xsql="SELECT * FROM think_role ";
        //$xlist=$Model2->query($xsql);
        $xlist = $Model2->where("id=$role_id")->select();
        if ($xlist === FALSE) {
            $this->error("读取数据失败。。。");
        }
        $vo[role_name] = $xlist[0][name];


        // 取节点表
        $Model2 = M('node');
        //$xsql="SELECT * FROM think_user ";
        unset($xlist);
        //$xlist=$Model2->query($xsql);
        $xlist = $Model2->where("pid=0")->select();
        if ($xlist === FALSE) {
            $this->error("读取数据失败。。。");
        }
        unset($nodelist);
        $nodelist = array();
        $i = 0;
        foreach ($xlist as $key => $value) {
            $node_id = $value[id];
            $nodelist[$i][id] = $node_id;
            $nodelist[$i][name] = $value[name];
            $nodelist[$i][title] = $value[title];
            $nodelist[$i][pid] = $value[pid];
            $nodelist[$i][level] = $value[level];
            $nodelist[$i][group_id] = $value[group_id];
            $nodelist[$i][ss] = "[" . $value[name] . "--" . $value[title] . "]";
            $nodelist[$i][vv] = $value[id] . "#" . $value[level] . "#" . $value[pid];

            $i++;
            $xlist2 = $Model2->where("pid=$node_id")->select();
            if ($xlist2 === FALSE) {
                $this->error("读取数据失败。。。");
            }
            foreach ($xlist2 as $key2 => $value2) {
                $node_id2 = $value2[id];
                $nodelist[$i][id] = $node_id2;
                $nodelist[$i][name] = $value2[name];
                $nodelist[$i][title] = $value2[title];
                $nodelist[$i][pid] = $value2[pid];
                $nodelist[$i][level] = $value2[level];
                $nodelist[$i][group_id] = $value2[group_id];
                $nodelist[$i][ss] = "----[" . $value2[name] . "--" . $value2[title] . "]";
                $nodelist[$i][vv] = $value2[id] . "#" . $value2[level] . "#" . $value2[pid];
                $i++;
                $xlist3 = $Model2->where("pid=$node_id2")->select();
                if ($xlist3 === FALSE) {
                    $this->error("读取数据失败。。。");
                }
                foreach ($xlist3 as $key3 => $value3) {
                    $node_id3 = $value3[id];
                    $nodelist[$i][id] = $node_id3;
                    $nodelist[$i][name] = $value3[name];
                    $nodelist[$i][title] = $value3[title];
                    $nodelist[$i][pid] = $value3[pid];
                    $nodelist[$i][level] = $value3[level];
                    $nodelist[$i][group_id] = $value3[group_id];
                    //$nodelist[$i][ss]="----------".$value3[name]."--".$value3[title]."--".$value3[group_id];
                    $nodelist[$i][ss] = "----------[" . $value3[name] . "--" . $value3[title] . "]";
                    $nodelist[$i][vv] = $value3[id] . "#" . $value3[level] . "#" . $value3[pid];
                    $i++;
                }
            }
        }

        // 取分组表
        $Model2 = M('group');
        unset($xlist);
        $xlist = $Model2->select();
        if ($xlist === FALSE) {
            $this->error("读取数据失败。。。");
        }
        foreach ($nodelist as $key => $value) {
            $group_id = $value["group_id"];
            $nodelist[$key]['group_name'] = $group_id;
            foreach ($xlist as $key2 => $value2) {
                if ($value2[id] == $group_id) {
                    $nodelist[$key]['group_name'] = $value2['name'] . "--" . $value2['title'];
                    $nodelist[$key][ss].="--[" . $nodelist[$key]['group_name'] . "]";
                }
            }
        }

        $this->assign('nodelist', $nodelist);
        /*
          echo "<pre>";
          print_r($nodelist);
          echo "</pre>";
          exit;
         */
        //if (count($xlist)==0) {
        //	$this->error("用户不存在，不能修改，请删除。。。");
        //}
        //$vo[account]=$xlist[0]['account'];
        //$vo[nickname]=$xlist[0]['nickname'];
        $this->assign('vo', $vo);

        // 取角色表
        $Model2 = M('role');
        //$xsql="SELECT * FROM think_role ";
        //$xlist=$Model2->query($xsql);
        $xlist = $Model2->select();
        if ($xlist === FALSE) {
            $this->error("读取数据失败。。。");
        }
        //$this->assign('vrole',$xlist);

        $this->display();
    }

    function update() {
        // 修改
        //$this->error('编辑失败aaaaaa!');
        //exit;
        $role_node = $this->_post('role_node');
        $x1 = explode("#", $role_node);
        $node_id = $x1[0];
        $level = $x1[1];
        $pid = $x1[2];
        $role_id = $this->_post('role_id');
        unset($x1);
        //$this->error('用户添加失败！'.$node_id);
        $Form = M($this->getActionName());
        // 获取标题 
        $title = $Form->where("role_id=$role_id and node_id=$node_id and pid=$pid and level=$level ")->getField('node_id');
        if (count($title) <> 0) {
            $this->error('该角色的节点已经添加，请重新选择！');
        }

        $name = $this->getActionName();
        $model = D($name);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        // 更新数据
        $model->node_id = $node_id;
        $model->level = $level;
        $model->pid = $pid;
        $list = $model->save();
        if (false !== $list) {
            //成功提示
            $this->success('编辑成功!', cookie('_currentUrl_'));
        } else {
            //错误提示
            $this->error('编辑失败!');
        }
    }

    public function index() {
        //列表过滤器，生成查询Map对象
        $map = $this->_search();
        if (method_exists($this, '_filter')) {
            $this->_filter($map);
        }
        $name = $this->getActionName();
        //echo "++=== $name <br />";
        $model = D($name);
        if (!empty($model)) {
            $this->_list($model, $map);
        }
        $this->display();
        return;
    }

    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
      +----------------------------------------------------------
     * @return void
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _list($model, $map, $sortBy = '', $asc = false) {
        //排序字段 默认为主键名
        //$name = $this->getActionName();
        //$model = M("access");
        //$p=$_REQUEST[C('VAR_PAGE')];
        //echo "==111 == $p </br>";

        if (!empty($_REQUEST ['_order'])) {
            $order = $_REQUEST ['_order'];
        } else {
            $order = !empty($sortBy) ? $sortBy : $model->getPk();
        }
        //排序方式默认按照倒序排列
        //接受 sost参数 0 表示倒序 非0都 表示正序
        if (isset($_REQUEST ['_sort'])) {
//			$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
            $sort = $_REQUEST ['_sort'] == 'asc' ? 'asc' : 'desc'; //zhanghuihua@msn.com
        } else {
            $sort = $asc ? 'asc' : 'desc';
        }
        //取得满足条件的记录数
        $count = $model->where($map)->count('id');
        //$count = $model->count('id');
        //echo "=== $count ==  <br />";
        //dump($map);
        if ($count > 0) {
            import("@.ORG.Util.Page");
            //import("ORG.Util.Page");
            //创建分页对象
            if (!empty($_REQUEST ['listRows'])) {
                $listRows = $_REQUEST ['listRows'];
            } else {
                $listRows = '';
            }
            $p = new Page($count, $listRows);
            //分页查询数据

            $voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
            //$voList = $model->limit($p->firstRow . ',' . $p->listRows)->select();
            //print_r($voList);
            //exit;
            //echo $model->getlastsql();
            //分页跳转的时候保证查询条件
            foreach ($map as $key => $val) {
                if (!is_array($val)) {
                    $p->parameter .= "$key=" . urlencode($val) . "&";
                }
            }
            //分页显示
            $page = $p->show();
            //列表排序显示
            $sortImg = $sort; //排序图标
            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式
            // 取角色表
            $Model2 = M('role');
            //$xsql="SELECT * FROM think_role ";
            //$xlist=$Model2->query($xsql);
            $xlist = $Model2->select();
            if ($xlist === FALSE) {
                $this->error("读取数据失败。。。");
            }
            foreach ($voList as $key => $value) {
                $role_id = $value["role_id"];
                $voList[$key]['role_name'] = "";
                foreach ($xlist as $key2 => $value2) {
                    if ($value2[id] == $role_id) {
                        $voList[$key]['role_name'] = $value2['name'];
                    }
                }
            }
            // 取节点表
            $Model2 = M('node');
            unset($xlist);
            $xlist = $Model2->select();
            if ($xlist === FALSE) {
                $this->error("读取数据失败。。。");
            }
            foreach ($voList as $key => $value) {
                $note_id = $value["node_id"];
                $voList[$key]['node_name'] = "";
                foreach ($xlist as $key2 => $value2) {
                    if ($value2[id] == $note_id) {
                        $voList[$key]['node_name'] = $value2['name'] . "--" . $value2['title'];
                        $voList[$key]['group_id'] = $value2['group_id'];
                    }
                }
            }

            // 取分组表
            $Model2 = M('group');
            unset($xlist);
            $xlist = $Model2->select();
            if ($xlist === FALSE) {
                $this->error("读取数据失败。。。");
            }
            foreach ($voList as $key => $value) {
                $group_id = $value["group_id"];
                $voList[$key]['group_name'] = "";
                foreach ($xlist as $key2 => $value2) {
                    if ($value2[id] == $group_id) {
                        $voList[$key]['group_name'] = $value2['name'] . "--" . $value2['title'];
                    }
                }
            }

//print_r($xlist);
            //模板赋值显示
            //dump($voList);
            //exit;
            $this->assign('list', $voList);
            $this->assign('sort', $sort);
            $this->assign('order', $order);
            $this->assign('sortImg', $sortImg);
            $this->assign('sortType', $sortAlt);
            $this->assign("page", $page);
        }

        //zhanghuihua@msn.com
        $this->assign('totalCount', $count);
        $this->assign('numPerPage', $p->listRows);
        $this->assign('currentPage', !empty($_REQUEST[C('VAR_PAGE')]) ? $_REQUEST[C('VAR_PAGE')] : 1);

        cookie('_currentUrl_', __SELF__);
        return;
    }

    public function add() {
        // 添加数据程序
        //echo "kkkk <br />";
        //exit;
        /*
          $x1=$this->getActionName();
          if ($x1=="Link"){
          // 取图片项目数据
          $xsql="select * from ebuy158_jpgtype order by sort ";
          //echo "$xsql <br />";
          $Model=M();
          $xlist=$Model->query($xsql);
          if ($xlist===FALSE){
          //echo "插入数据失败 $xsql2 <br />";
          $this->error("读取数据失败。。。".$xsql);
          }
          $this->assign('typelist', $xlist);
          //print_r($xlist);
          //exit;
          }
         */
        // 取角色表
        $Model2 = M('role');
        //$xsql="SELECT * FROM think_role ";
        //$xlist=$Model2->query($xsql);
        $xlist = $Model2->select();
        if ($xlist === FALSE) {
            $this->error("读取数据失败。。。");
        }
        $this->assign('vrole', $xlist);

        // 取节点表
        $Model2 = M('node');
        //$xsql="SELECT * FROM think_user ";
        unset($xlist);
        //$xlist=$Model2->query($xsql);
        $xlist = $Model2->where("pid=0")->select();
        if ($xlist === FALSE) {
            $this->error("读取数据失败。。。");
        }
        unset($nodelist);
        $nodelist = array();
        $i = 0;
        foreach ($xlist as $key => $value) {
            $node_id = $value[id];
            $nodelist[$i][id] = $node_id;
            $nodelist[$i][name] = $value[name];
            $nodelist[$i][title] = $value[title];
            $nodelist[$i][pid] = $value[pid];
            $nodelist[$i][level] = $value[level];
            $nodelist[$i][group_id] = $value[group_id];
            $nodelist[$i][ss] = "[" . $value[name] . "--" . $value[title] . "]";
            $nodelist[$i][vv] = $value[id] . "#" . $value[level] . "#" . $value[pid];

            $i++;
            $xlist2 = $Model2->where("pid=$node_id")->select();
            if ($xlist2 === FALSE) {
                $this->error("读取数据失败。。。");
            }
            foreach ($xlist2 as $key2 => $value2) {
                $node_id2 = $value2[id];
                $nodelist[$i][id] = $node_id2;
                $nodelist[$i][name] = $value2[name];
                $nodelist[$i][title] = $value2[title];
                $nodelist[$i][pid] = $value2[pid];
                $nodelist[$i][level] = $value2[level];
                $nodelist[$i][group_id] = $value2[group_id];
                $nodelist[$i][ss] = "----[" . $value2[name] . "--" . $value2[title] . "]";
                $nodelist[$i][vv] = $value2[id] . "#" . $value2[level] . "#" . $value2[pid];
                $i++;
                $xlist3 = $Model2->where("pid=$node_id2")->select();
                if ($xlist3 === FALSE) {
                    $this->error("读取数据失败。。。");
                }
                foreach ($xlist3 as $key3 => $value3) {
                    $node_id3 = $value3[id];
                    $nodelist[$i][id] = $node_id3;
                    $nodelist[$i][name] = $value3[name];
                    $nodelist[$i][title] = $value3[title];
                    $nodelist[$i][pid] = $value3[pid];
                    $nodelist[$i][level] = $value3[level];
                    $nodelist[$i][group_id] = $value3[group_id];
                    //$nodelist[$i][ss]="----------".$value3[name]."--".$value3[title]."--".$value3[group_id];
                    $nodelist[$i][ss] = "----------[" . $value3[name] . "--" . $value3[title] . "]";
                    $nodelist[$i][vv] = $value3[id] . "#" . $value3[level] . "#" . $value3[pid];
                    $i++;
                }
            }
        }

        // 取分组表
        $Model2 = M('group');
        unset($xlist);
        $xlist = $Model2->select();
        if ($xlist === FALSE) {
            $this->error("读取数据失败。。。");
        }
        foreach ($nodelist as $key => $value) {
            $group_id = $value["group_id"];
            $nodelist[$key]['group_name'] = $group_id;
            foreach ($xlist as $key2 => $value2) {
                if ($value2[id] == $group_id) {
                    $nodelist[$key]['group_name'] = $value2['name'] . "--" . $value2['title'];
                    $nodelist[$key][ss].="--[" . $nodelist[$key]['group_name'] . "]";
                }
            }
        }

        $this->assign('nodelist', $nodelist);
        $this->display();
    }

    // 插入数据
    public function insert() {
        // 创建数据对象
        $role_node = $this->_post('role_node');
        $x1 = explode("#", $role_node);
        $node_id = $x1[0];
        $level = $x1[1];
        $pid = $x1[2];
        $role_id = $this->_post('role_id');
        unset($x1);
        //$this->error('用户添加失败！'.$node_id);
        $Form = M($this->getActionName());
        // 获取标题 
        $title = $Form->where("role_id=$role_id and node_id=$node_id and pid=$pid and level=$level ")->getField('node_id');
        if (count($title) <> 0) {
            $this->error('该角色的节点已经添加，请重新选择！');
        }
        $User = D($this->getActionName());
        if (!$User->create()) {
            $this->error($User->getError());
        } else {
            // 写入帐号数据
            $User->node_id = $node_id;
            $User->level = $level;
            $User->pid = $pid;
            if ($result = $User->add()) {
                $this->success('角色_节点添加成功！');
            } else {
                $this->error('角色_节点添加失败！');
            }
        }
    }

    protected function addRole($userId) {
        //新增用户自动加入相应权限组
        $RoleUser = M("RoleUser");
        $RoleUser->user_id = $userId;
        // 默认加入网站编辑组
        $RoleUser->role_id = 2;
        $RoleUser->add();
    }

    //重置密码
    public function resetPwd() {
        $id = $_POST['id'];
        $password = $_POST['password'];
        if ('' == trim($password)) {
            $this->error('密码不能为空！');
        }
        $User = M('User');
        $User->password = md5($password);
        $User->id = $id;
        $result = $User->save();
        if (false !== $result) {
            $this->success("密码修改为$password");
        } else {
            $this->error('重置密码失败！');
        }
    }

}